package com.dayaokeji.rhythmschoolstudent.client.message;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;

import com.beetle.bauhinia.gallery.GalleryImage;
import com.dayaokeji.imkitwrapper.fragment.ChatFragment;
import com.dayaokeji.imkitwrapper.fragment.MessageFragment;
import com.dayaokeji.rhythmschoolstudent.R;
import com.dayaokeji.rhythmschoolstudent.client.common.base.common.ApiConstantKt;
import com.dayaokeji.rhythmschoolstudent.client.common.base.common.BaseActivity;
import com.dayaokeji.rhythmschoolstudent.utils.ObjectUtils;
import com.dayaokeji.rhythmschoolstudent.utils.ServerCallback;
import com.dayaokeji.rhythmschoolstudent.utils.ToastUtils;
import com.dayaokeji.rhythmschoolstudent.utils.UserUtils;
import com.dayaokeji.server_api.ApiUtils;
import com.dayaokeji.server_api.ServerResponse;
import com.dayaokeji.server_api.api.GroupApi;
import com.dayaokeji.server_api.api.UserApi;
import com.dayaokeji.server_api.domain.UserInfo;
import com.orhanobut.logger.Logger;

import java.util.ArrayList;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;
import retrofit2.Call;

public class ChatActivity extends BaseActivity {

    private static final String CHAT_FRAGMENT_FLAG = "chat_flag";

    private static final String EXTRA_RECEIVER_ID = "receiver_id";
    private static final String EXTRA_RECEIVER_NAME = "receiver_name";

    @BindView(R.id.toolbar)
    Toolbar toolbar;

    private Fragment chatFragment;
    private long receiverId;
    private String receiverName;

    private UserApi userApi = ApiUtils.getApi(UserApi.class);
    private Call<ServerResponse<UserInfo>> userDetailCall;


    public static void navigation(Context context,long receiverId,String receiverName) {
        final Intent intent = new Intent(context, ChatActivity.class);
        intent.putExtra(EXTRA_RECEIVER_ID, receiverId);
        intent.putExtra(EXTRA_RECEIVER_NAME, receiverName);
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_chat);
        setSupportActionBar(toolbar);
        init();
    }

    private void init(){
        final Intent intent = getIntent();
        receiverId = intent.getLongExtra(EXTRA_RECEIVER_ID, 0);
        receiverName = intent.getStringExtra(EXTRA_RECEIVER_NAME);

        if (receiverId == 0) {
            Logger.d("receiver id is 0");
            ToastUtils.info("聊天数据异常");
            return;
        }

        if (TextUtils.isEmpty(receiverName)) {
            Logger.d("receiver name is null");
            ToastUtils.info("聊天数据异常");
            return;
        }

        setupView();
    }

    private void setupView() {
        if (getSupportActionBar() != null) {
            getSupportActionBar().setTitle(receiverName);
        }
        chatFragment = getSupportFragmentManager().findFragmentByTag(CHAT_FRAGMENT_FLAG);
        if (chatFragment == null) {
            chatFragment = ChatFragment.newInstance(UserUtils.getCurrentUid(), receiverId);
        }
        getSupportFragmentManager().beginTransaction().replace(R.id.fl_content, chatFragment).commit();

        addDisposable(Observable.interval(3, TimeUnit.SECONDS).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Consumer<Long>() {
            @Override
            public void accept(Long aLong) throws Exception {
                if (((ChatFragment)chatFragment).refreshConnectState()) {
                    toolbar.setSubtitle("");
                }else{
                    toolbar.setSubtitle("正在连接...");
                }
            }
        }));

        ((ChatFragment)chatFragment).setImgPickerClickListener(new MessageFragment.ImgPickerClickListener() {
            @Override
            public void onClick(ArrayList<GalleryImage> galleryImages, int position) {
                GalleryActivity.navigation(ChatActivity.this, galleryImages, position);
            }
        });

        ((ChatFragment) chatFragment).setUserInfoCallback(new MessageFragment.UserInfoCallback() {
            @SuppressLint("DefaultLocale")
            @Override
            public void callback(final long uid, final MessageFragment.GetUserCallback callback) {
                if (uid != 0) {
                    userDetailCall = userApi.userDetail(uid);
                    userDetailCall.enqueue(new ServerCallback<UserInfo>() {
                        @Override
                        public void onResponse(boolean success, ServerResponse<UserInfo> response) {
                            if (success) {
                                MessageFragment.User user = new MessageFragment.User();
                                user.uid = uid;
                                Logger.d("im user name === "+user.name);
                                if (response.getBody() != null) {
                                    UserInfo userInfo = response.getBody();
                                    user.identifier = userInfo.getName();
                                    user.name = userInfo.getName();
                                    user.avatarURL = ApiConstantKt.getRemoteImageUrl()+(TextUtils.isEmpty(userInfo.getPictureId()) ? "" : userInfo.getPictureId());
                                }else{
                                    user.name = String.format("%d", uid);
                                    user.avatarURL = "";
                                }
                                callback.onUser(user);
                            }
                        }
                    });
                }else{
                    MessageFragment.User user = new MessageFragment.User();
                    user.uid = uid;
                    user.identifier = String.format("%d", uid);
                    UserInfo userInfo = UserUtils.getUserInfo();
                    if (userInfo != null) {
                        user.name = userInfo.getName() == null ? "" : userInfo.getName();
                        user.avatarURL = ApiConstantKt.getRemoteImageUrl()+(TextUtils.isEmpty(userInfo.getPictureId()) ? "" : userInfo.getPictureId());
                    }
                    callback.onUser(user);
                }
            }
        });
    }
}
